// import store from '../store'
import dictMgr from '@/biz/building/dict.js'
import buildMgr from '@/biz/building'
import userMgr from '@/biz/user'

Function.prototype.method = function (name, fn) {
  this.prototype[name] = fn
  return this
}

Array.prototype.remove = function (item) {
  let idx = this.indexOf(item)
  if (idx > -1) {
    this.splice(idx, 1)
  }
}

if (!String.prototype.trim) {
  String.method('trim', function () {
    return this.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, '')
  })
}
var isType = function (type) {
  return function (obj) {
    return Object.prototype.toString.call(obj) == '[object ' + type + ']'
  }
}
var isArray = isType('Array')
var isStr = isType('String')
var isObject = isType('Object')
var isFun = isType('Function')
var isRegExp = isType('RegExp')
const TOOL = {
  isArray: isArray,
  isStr: isStr,
  isObject: isObject,
  isFun: isFun,
  isRegExp: isRegExp,
  extend: function () {
    var options,
      copyIsArray,
      target = arguments[0] || {},
      i = 1,
      length = arguments.length,
      deep = false

    if (typeof target === 'boolean') {
      deep = target
      target = arguments[i] || {}
      i++
    }
    if (i === length) {
      target = this
      i--
    }
    for (; i < length; i++) {
      if ((options = arguments[i]) != null) {
        for (let name in options) {
          let clone,
            src = target[name],
            copy = options[name]
          if (target === copy) continue
          if (deep && copy && (isObject(copy) || (copyIsArray = isArray(copy)))) {
            if (copyIsArray) {
              copyIsArray = false
              clone = src && isArray(src) ? src : []
            } else {
              clone = src && isObject(src) ? src : {}
            }
            target[name] = this.extend(deep, clone, copy)
          } else if (copy !== undefined) {
            target[name] = copy
          }
        }
      }
    }
    return target
  },

  // openLoading() {
  //   store.dispatch('saveIsLoading', true)
  // },
  // closeLoading() {
  //   store.dispatch('saveIsLoading', false)
  // },

  getStorage(item) {
    // 临时加
    if (item == 'dictionaryData') {
      return JSON.stringify(dictMgr.info())
    } else if (item == 'X-Token') {
      return userMgr.info() ? userMgr.info().token : ''
    } else if (item == 'userMess') {
      return JSON.stringify(userMgr.info())
    } else if (item == 'appId') {
      return 36
    } else if (item == 'buildMess') {
      return JSON.stringify(buildMgr.info())
    }

    var value = window.sessionStorage.getItem(item)
    if (value) {
      value = value
      if (value.indexOf('time') > -1) value = JSON.parse(value)
      if (value.time && value.expires) {
        //设置了过期时间
        let newTime = new Date().valueOf(),
          oldTime = value.time
        if (newTime - oldTime > value.expires) {
          window.sessionStorage.removeItem(item)
          value = ''
        } else {
          value = value.value ? value.value : value
        }
      }
    }
    return value
  },
  setStorage(obj) {
    for (var key in obj) {
      if (obj.hasOwnProperty(key)) {
        window.sessionStorage.setItem(key, String(obj[key]))
      }
    }
  },
  clearStorage(mess) {
    if (mess) {
      mess.forEach((item) => {
        window.sessionStorage.removeItem(item)
      })
    } else {
      window.sessionStorage.clear()
    }
  },

  getlocalStorage(item) {
    var value
    value = window.localStorage.getItem(item)
    return value ? value : ''
  },
  setlocalStorage(obj) {
    for (var key in obj) {
      if (obj.hasOwnProperty(key)) {
        window.localStorage.setItem(key, String(obj[key]))
      }
    }
  },
  clearlocalStorage() {
    function clearCookie() {
      var keys = document.cookie.match(/[^ =;]+(?=\=)/g)
      if (keys) {
        for (var i = keys.length; i--; ) document.cookie = keys[i] + '=0;expires=' + new Date(0).toUTCString()
      }
    }

    if (window.localStorage) {
      window.localStorage.clear()
    } else {
      clearCookie()
    }
    // return this;
  },
  encrypt(value) {
    var encryptValue = ''
    var mask
    var maskValue
    for (var i = 0, len = value.length; i < len; i++) {
      mask = Math.round(Math.random() * 111) + 77
      maskValue = value.charCodeAt(i) + mask
      mask += i
      encryptValue += String.fromCharCode(maskValue, mask)
    }
    return encryptValue
  },
  decrypt(value) {
    var decryptValue = ''
    var k = 0
    var v
    var m
    var decrypt = function (v, m, i) {
      v = v.charCodeAt(0)
      m = m.charCodeAt(0)
      m -= i
      v -= m
      return String.fromCharCode(v)
    }
    for (var i = 0, len = value.length; i < len; i++) {
      if (!(i % 2)) {
        v = value[i]
      } else {
        m = value[i]
        decryptValue += decrypt(v, m, k)
        k++
      }
    }
    return decryptValue
  },
  getToken() {
    return this.getStorage('X-Token') || ''
  },
  getCookie: function (name) {
    var arr,
      reg = new RegExp('(^| )' + name + '=([^;]*)(;|$)')
    if ((arr = document.cookie.match(reg))) return unescape(arr[2])
    else return null
  },
  setCookie: function (name, value, day) {
    if (day !== 0) {
      //当设置的时间等于0时，不设置expires属性，cookie在浏览器关闭后删除
      var expires = day * 24 * 60 * 60 * 1000
      var date = new Date(+new Date() + expires)
      document.cookie = name + '=' + escape(value) + ';expires=' + date.toUTCString()
    } else {
      document.cookie = name + '=' + escape(value)
    }
  },
  delCookie: function (name) {
    this.setCookie(name, ' ', -1)
  },
  copy: function (source) {
    let result = Array.isArray(source) ? [] : {}
    for (var key in source) {
      result[key] =
        source[key] != null && typeof source[key] === 'object' ? this.copy(source[key]) : source[key]
    }
    return result
  },
  getTime: function (t) {
    if (!t) return new Date().getTime()
    return new Date(String(t).replace(/-/g, '/')).getTime()
  },
  dateFtt: function (fmt, date) {
    if (typeof date === 'string' || typeof date === 'number') {
      date.indexOf('-') > -1 && (date = date.replace(/\-/g, '/'))
      date = new Date(date)
    }
    var o = {
      'M+': date.getMonth() + 1, //月份
      'd+': date.getDate(), //日
      'h+': date.getHours(), //小时
      'm+': date.getMinutes(), //分
      's+': date.getSeconds(), //秒
      'q+': Math.floor((date.getMonth() + 3) / 3), //季度
      S: date.getMilliseconds() //毫秒
    }
    if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length))
    for (var k in o)
      if (new RegExp('(' + k + ')').test(fmt))
        fmt = fmt.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k] : ('00' + o[k]).substr(('' + o[k]).length))
    return fmt
  },

  getUrlParams(name) {
    var url = ''
    if (window.location.search == '') {
      url = window.location.hash
    } else {
      url = window.location.search
    }

    // var url = window.location.search;
    // var url = window.location.hash;
    var n = url.indexOf('?')
    // if (url.indexOf('?') == 1) {
    //   return false;
    // }
    url = url.substr(n + 1)
    url = url.split('&')
    var name = name || ''
    var nameres
    for (var i = 0; i < url.length; i++) {
      var info = url[i].split('=')
      var obj = {}
      obj[info[0]] = decodeURI(info[1])
      url[i] = obj
    }
    if (name) {
      for (var i = 0; i < url.length; i++) {
        for (const key in url[i]) {
          if (key == name) {
            nameres = url[i][key]
          }
        }
      }
    } else {
      nameres = url
    }
    return nameres
  },
  // 时间格式转换 2021-08-02 00:00:00 => 2021-08-02
  formatterDate(date, num = 10) {
    if (!date) return date
    return date.slice(0, num)
  },
  //  数组扁平化
  flattenArr(arr) {
    return arr.reduce((result, item) => {
      return result.concat(item, Array.isArray(item.children) ? TOOL.flattenArr(item.children) : [])
    }, [])
  },
  //数组对象深拷贝
  deepClone: function (obj) {
    let objClone = Array.isArray(obj) ? [] : {}
    if (obj && typeof obj === 'object') {
      for (let key in obj) {
        if (obj.hasOwnProperty(key)) {
          //判断ojb子元素是否为对象，如果是，递归复制
          if (obj[key] && typeof obj[key] === 'object') {
            objClone[key] = this.deepClone(obj[key])
          } else {
            //如果不是，简单复制
            objClone[key] = obj[key]
          }
        }
      }
    }
    return objClone
  },
  //数组对象合并 obj 查询条件  options 表头筛选
  mergeObject: function (obj, options) {
    for (var objKey in obj) {
      for (var optionKey in options) {
        if (objKey == optionKey) {
          obj[objKey] = options[optionKey]
        }
      }
    }
    return obj
  },
  /**
   * 数组去重
   * @params arr 要去重的数组
   * @params pro 数组中对象的某个属性
   * @returns arr 去重后的数组
   */
  noRepeatObj: function (arr, pro) {
    var hash = {}
    arr = arr.reduce(function (item, next) {
      hash[next[pro]] ? '' : (hash[next[pro]] = true && item.push(next))
      return item
    }, [])
    return arr
  },
  //手机号隐藏四位
  repPhoneNum(val) {
    if (val) {
      return val.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2')
    } else {
      return '-'
    }
  },
  //掩号转*号
  maskPhoneNum(val) {
    if (val) {
      let str = val.substring(3, 7)
      let reg = /^0?1[3|4|5|6|7|8][0-9]\d{8}$/
      if (!reg.test(val)) {
        if (!Number(str)) {
          return val.replace(val.substring(3, 7), '****')
        }
      } else {
        return val
      }
    } else {
      return '-'
    }
  },
  // EXLCL
  isExcel(type, name, data) {
    const link = document.createElement('a')
    const blob = new Blob([data])
    link.style.display = 'none'
    link.href = URL.createObjectURL(blob)
    link.setAttribute('download', `${name}.` + type)
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
  },

  getTimeRi(n) {
    //本周、上周
    var now = new Date()
    var year = now.getFullYear()
    //因为月份是从0开始的,所以获取这个月的月份数要加1才行
    var month = now.getMonth() + 1
    var date = now.getDate() //日期
    var day = now.getDay() //星期
    // console.log(date);
    //判断是否为周日,如果不是的话,就让今天的day-1(例如星期二就是2-1)
    if (day !== 0) {
      n = n + (day - 1)
    } else {
      n = n + day
    }
    if (day) {
      //这个判断是为了解决跨年的问题
      if (month > 1) {
        month = month
      }
      //这个判断是为了解决跨年的问题,月份是从0开始的
      else {
        year = year - 1
        month = 12
      }
    }
    now.setDate(now.getDate() - n)

    year = now.getFullYear()
    month = now.getMonth() + 1
    date = now.getDate()
    // console.log(n);
    let s = year + '-' + (month < 10 ? '0' + month : month) + '-' + (date < 10 ? '0' + date : date)
    return s
  },

  getDayRi(day) {
    var today = new Date()
    var targetday_milliseconds = today.getTime() + 1000 * 60 * 60 * 24 * day
    today.setTime(targetday_milliseconds) //注意，这行是关键代码
    var tYear = today.getFullYear()
    var tMonth = today.getMonth() + 1
    var tDate = today.getDate()
    tMonth = tMonth < 10 ? '0' + tMonth : tMonth
    tDate = tDate < 10 ? '0' + tDate : tDate
    return tYear + '-' + tMonth + '-' + tDate
  },

  getMonthStartAndEnd(AddMonthCount) {
    //起止日期数组
    var startStop = new Array()
    //获取当前时间
    var currentDate = new Date()
    var month = currentDate.getMonth() + AddMonthCount
    if (month < 0) {
      var n = parseInt(-month / 12)
      month += n * 12
      currentDate.setFullYear(currentDate.getFullYear() - n)
    }
    currentDate = new Date(currentDate.setMonth(month))
    //获得当前月份0-11
    var currentMonth = currentDate.getMonth()
    //获得当前年份4位年
    var currentYear = currentDate.getFullYear()
    //获得上一个月的第一天
    var currentMonthFirstDay = new Date(currentYear, currentMonth, 1)
    //获得上一月的最后一天
    var currentMonthLastDay = new Date(currentYear, currentMonth + 1, 0)
    //添加至数组
    startStop.push(this.formatDate(currentMonthFirstDay))
    startStop.push(this.formatDate(currentMonthLastDay))
    //返回
    return startStop
  },
  formatDate(date) {
    var year = ''
    var month = ''
    var day = ''
    var now = date
    year = '' + now.getFullYear()
    if (now.getMonth() + 1 < 10) {
      month = '0' + (now.getMonth() + 1)
    } else {
      month = '' + (now.getMonth() + 1)
    }
    if (now.getDate() < 10) {
      day = '0' + now.getDate()
    } else {
      day = '' + now.getDate()
    }
    return year + '-' + month + '-' + day
  },

  timeSub(time) {
    return time.substring(0, time.length - 3)
  },
  //近30天
  lastThirty() {
    var now = new Date()
    var year = now.getFullYear()
    var month = now.getMonth() + 1 //0-11表示1-12月
    var day = now.getDate()
    var dateObj = {}
    dateObj.now = year + '-' + month + '-' + day
    var nowMonthDay = new Date(year, month, 0).getDate() //当前月的总天数
    if (month - 1 <= 0) {
      //如果是1月，年数往前推一年<br>
      dateObj.last = year - 1 + '-' + 12 + '-' + day
    } else {
      var lastMonthDay = new Date(year, parseInt(month) - 1, 0).getDate()
      if (lastMonthDay < day) {
        // 1个月前所在月的总天数小于现在的天日期
        if (day < nowMonthDay) {
          //当前天日期小于当前月总天数
          dateObj.last = year + '-' + (month - 1) + '-' + (lastMonthDay - (nowMonthDay - day))
        } else {
          dateObj.last = year + '-' + (month - 1) + '-' + lastMonthDay
        }
      } else {
        dateObj.last = year + '-' + (month - 1) + '-' + day
      }
    }
    return [dateObj.last, dateObj.now]
  },
  // 当前月
  currentMonth() {
    var myDate = new Date()
    var tYear = myDate.getFullYear()
    var tMonth = myDate.getMonth() + 1 >= 10 ? myDate.getMonth() + 1 : '0' + (myDate.getMonth() + 1)
    const pre = tYear + '-' + tMonth + '-01'
    const cur = TOOL.formatDate(myDate)
    return [pre, cur]
  },
  // 当前周
  currentWeek() {
    var myDate = new Date()
    // var tYear = myDate.getFullYear();
    // var tMonth = (myDate.getMonth() + 1) >= 10 ? myDate.getMonth() + 1 : '0' + (myDate.getMonth() + 1);

    var day = myDate.getDay()
    var deltaDay
    if (day == 0) {
      deltaDay = 6
    } else {
      deltaDay = day - 1
    }
    const pre = TOOL.formatDate(new Date(myDate.getTime() - deltaDay * 24 * 60 * 60 * 1000))
    const cur = TOOL.formatDate(myDate)
    return [pre, cur]
  },
  // objIfNull(obj) { // 判断一个对象下是否有空属性
  //   for (const key in obj) {
  //     if (obj.hasOwnProperty(key)) {
  //       if (obj[key] === null || obj[key] === '') {
  //         return false;
  //       }
  //     }
  //   }
  // },

  isRepeat(arr) {
    var obj = {}

    for (var i in arr) {
      //存在重复值
      if (obj[arr[i]]) return true

      obj[arr[i]] = true
    }
    //不重复
    return false
  },

  /**
   * @desc 函数防抖
   * @param func 函数
   * @param wait 延迟执行毫秒数
   * @param immediate true 表立即执行，false 表非立即执行
   */
  debounce(func, wait, immediate = false) {
    let timeout

    return function () {
      let context = this
      let args = arguments

      if (timeout) clearTimeout(timeout)
      if (immediate) {
        var callNow = !timeout
        timeout = setTimeout(() => {
          timeout = null
        }, wait)
        if (callNow) func.apply(context, args)
      } else {
        timeout = setTimeout(function () {
          func.apply(context, args)
        }, wait)
      }
    }
  },
  /**
   * @desc 函数节流
   * @param func 函数
   * @param wait 延迟执行毫秒数
   * @param type 1 表时间戳版，2 表定时器版
   */
  throttle(func, wait, type) {
    let previous = 0,
      timeout = null
    if (type === 1) {
      previous = 0
    } else if (type === 2) {
      timeout
    }
    return function () {
      let context = this
      let args = arguments
      if (type === 1) {
        let now = Date.now()

        if (now - previous > wait) {
          func.apply(context, args)
          previous = now
        }
      } else if (type === 2) {
        if (!timeout) {
          timeout = setTimeout(() => {
            timeout = null
            func.apply(context, args)
          }, wait)
        }
      }
    }
  },
  /**
   * 特殊字符校验
   */
  unNormalReg(parmas) {
    var regEn = /[`~!@#$%^&*()_+<>?:"{}, .\/;'[\]]/im,
      regCn = /[·！#￥（——）：；“”‘、，| 《。》？、【】[\]]/im
    return regEn.test(parmas) || regCn.test(parmas)
  },
  /**
   * 获取元素到顶部距离-通用方法
   *
   */
  getPositionTop(node) {
    if (node) {
      var top = node.offsetTop
      var parent = node.offsetParent
      while (parent != null) {
        top += parent.offsetTop
        parent = parent.offsetParent
      }
      return top
    } else {
      return 0
    }
  },
  /**
   *
   * @param {*} node 获取元素到左侧距离-通用方法
   * @returns
   */
  getPositionLeft(node) {
    var left = node.offsetLeft
    var parent = node.offsetParent
    while (parent != null) {
      left += parent.offsetLeft
      parent = parent.offsetParent
    }
    return left
  },
  /**
   * 获取table高度
   * 40 表格头部的高度
   * 10 横向滚动条的高度
   * 60 分页的高度
   * 100 暂无数据高度处理
   * UVal  需要特别处理的情况  针对实际内容区的高度不以window.innerHeight为基准 如组织管理的边框
   */
  getTableHeight(node, UVal = 0) {
    let scrollWidth =
      node.$children[1].$el.clientWidth + TOOL.getPositionLeft(node.$el) > window.innerWidth ? 10 : 0
    let resizeHeight =
      node.$children[1].$el.clientHeight + 40 + scrollWidth >
      window.innerHeight - TOOL.getPositionTop(node.$el) - 60
        ? window.innerHeight - TOOL.getPositionTop(node.$el) - 60 - UVal
        : node.$children[1].$el.clientHeight + 40 + scrollWidth < 100
        ? 100
        : node.$children[1].$el.clientHeight + 40 + scrollWidth
    return resizeHeight
  },
  /**
   * 图片压缩
   * @param {文件} file
   * quality 压缩质量
   */
  compressImg(file, quality) {
    return new Promise((resolve, reject) => {
      var img = new Image()
      //获取原图的base64
      var reader = new FileReader()
      reader.onload = function (e) {
        img.src = e.target.result
      }
      reader.readAsDataURL(file)

      img.onload = function () {
        // 当图片宽度超过 700px 时, 就压缩成 700px, 高度按比例计算 // 压缩质量可以根据实际情况调整
        var w = Math.min(700, img.width)
        var h = img.height * (w / img.width)
        var canvas = document.createElement('canvas')
        var ctx = canvas.getContext('2d')
        canvas.width = w
        canvas.height = h
        ctx.drawImage(img, 0, 0, w, h)
        //将canvas转成base64第二个参数是设置质量（越大越好最大1）
        let newFile = TOOL.base64UrlToBlob(canvas.toDataURL('image/jpg', quality), file.name)
        resolve(newFile)
      }
    })
  },
  /*这里转blob 转file*/
  base64UrlToBlob(urlData, name) {
    let arr = urlData.split(','),
      mime = arr[0].match(/:(.*?);/)[1], // 去掉url的头，并转化为byte
      bstr = atob(arr[1]), // 处理异常,将ascii码小于0的转换为大于0
      n = bstr.length,
      u8arr = new Uint8Array(n)
    while (n--) {
      u8arr[n] = bstr.charCodeAt(n)
    }
    //转file
    return new File([u8arr], name, {
      type: mime
    })
    // 转Blob
    // return new Blob([u8arr], { type: mime, name: name, lastModified: Date.now() });
  },

  // 判断日期差
  dateDiff(d1, d2) {
    console.log(d1, d2, 'aaaaaaaaaaaaaaaaaaaaaaaaaa')
    d1 = new Date(d1.replace(/-/g, '/'))
    d2 = new Date(d2.replace(/-/g, '/'))
    var obj = {},
      M1 = d1.getMonth(),
      D1 = d1.getDate(),
      M2 = d2.getMonth(),
      D2 = d2.getDate()
    obj.Y = d2.getFullYear() - d1.getFullYear() + (M1 * 100 + D1 > M2 * 100 + D2 ? -1 : 0)
    obj.M = (obj.Y > 0 ? obj.Y * 12 : 12) + M2 - M1 + (D1 > D2 ? -1 : 0)
    obj.s = Math.floor((d2 - d1) / 1000) //差几秒
    obj.m = Math.floor(obj.s / 60) //差几分钟
    obj.h = Math.floor(obj.m / 60) //差几小时
    obj.D = Math.floor(obj.h / 24) //差几天
    return obj
  },

  // 空数据转换成-
  transformationNull(obj) {
    Object.keys(obj).map(function (key) {
      ;(obj[key] == null || obj[key] === '') && (obj[key] = '-') //比较key
    })
  },
  // 接口传参-换成null
  transformationNullSet(obj) {
    Object.keys(obj).map(function (key) {
      obj[key] == '-' && !key.includes('_txt_') && (obj[key] = null) //比较key
    })
  },

  //   金额转换成三位分割法
  formatterMoney(val) {
    return val != '-' && val != undefined
      ? Number(val).toLocaleString().includes('.')
        ? Number(val).toLocaleString()
        : Number(val).toLocaleString() + '.00'
      : '-'
  },
  // 将数字转化为千分位，三位以逗号隔开
  formatNumtoLocaleString: function (num) {
    if (num) {
      return parseFloat(num).toLocaleString()
    }
    return num
  },
  // 数字转中文
  convertToChinese: function (num) {
    var N = ['零', '一', '二', '三', '四', '五', '六', '七', '八', '九']
    var str = num.toString()
    var len = num.toString().length
    var C_Num = []
    for (var i = 0; i < len; i++) {
      C_Num.push(N[str.charAt(i)])
    }
    return C_Num.join('')
  },
  /**
   * @desc 计算结果失去精度处理
   * @param value 数值（计算结果）
   * @return 处理后的数值
   */
  precision(value) {
    let len = String(value).split('.')[0].length + 4
    return Number(value.toPrecision(len))
  },
  /**
   * @desc 数组通过Id值从小到大排序
   * @param arr 需要处理的数组 key Id值
   * @return 处理后的数组
   */
  bubbleSort(arr, key) {
    var i = arr.length,
      j
    var tempExchangVal
    while (i > 0) {
      for (j = 0; j < i - 1; j++) {
        if (arr[j][key] > arr[j + 1][key]) {
          tempExchangVal = arr[j]
          arr[j] = arr[j + 1]
          arr[j + 1] = tempExchangVal
        }
      }
      i-- //因为是从整个数组长度开始递减操作的
    }
    return arr
  },
  handleDateRange(val) {
    if (val && val.length == 2) {
      if (val[0].length > 0) {
        val[0] = val[0] ? (val[0].length <= 10 ? val[0] + ' 00:00:00' : val[0]) : ''
        val[1] = val[1] ? (val[1].length <= 10 ? val[1] + ' 23:59:59' : val[1]) : ''
      } else {
        // val[0] = null
        // val[1] = null
      }
    }
    return val
  },

  getUrlBase64(url) {
    return new Promise((resolve, reject) => {
      let canvas = document.createElement('canvas')
      const ctx = canvas.getContext('2d')
      let img = new Image()
      img.crossOrigin = 'Anonymous' //开启img的“跨域”模式
      img.src = url
      img.onload = function () {
        canvas.height = img.height
        canvas.width = img.width
        ctx.drawImage(img, 0, 0, img.width, img.height) //参数可自定义
        const dataURL = canvas.toDataURL('image/jpeg', 1) //获取Base64编码
        resolve(dataURL)
        canvas = null //清除canvas元素
        img = null //清除img元素
      }
      img.onerror = function () {
        reject(new Error('图片加载失败' + url))
      }
    })
  },

  rgbafun(img, c) {
    let ctxHeight = 20
    c.width = img.width
    c.height = img.height
    let ctx = c.getContext('2d')
    //getContext("2d") 对象是内建的 HTML5 对象，
    //拥有多种绘制路径、矩形、圆形、字符以及添加图像的方法。
    ctx.drawImage(img, 0, 0, c.width, c.height)
    //把图片画入画布(图片节点，左上角开始的x,y, 画入图片的宽，高, 矩形的左顶点横坐标 矩形的左顶点纵坐标 矩形的宽度 矩形的高度)

    let imgData = ctx.getImageData(0, 480, c.width, ctxHeight)
    //getImageDate 得到画布里的图片信息(画布的四个角)

    // 取所有像素的平均值
    let r = 0
    let g = 0
    let b = 0
    let a = 0
    for (let row = 0; row < ctxHeight; row++) {
      for (let col = 0; col < c.width; col++) {
        r += imgData.data[(c.width * row + col) * 4]
        g += imgData.data[(c.width * row + col) * 4 + 1]
        b += imgData.data[(c.width * row + col) * 4 + 2]
        a += imgData.data[(c.width * row + col) * 4 + 3]
      }
    }

    // 求取平均值
    r /= c.width * ctxHeight
    g /= c.width * ctxHeight
    b /= c.width * ctxHeight
    a /= c.width * ctxHeight

    // 将最终的值取整
    r = Math.round(r)
    g = Math.round(g)
    b = Math.round(b)
    a = Math.round(a)

    let rgba = {
      r,
      g,
      b,
      a
    }
    let rgbaColor = `rgba(${rgba.r},${rgba.g},${rgba.b},1)`
    // return rgba

    return new Promise((resolve, reject) => {
      resolve(rgbaColor)
    })
  },

  formatSeconds(value) {
    //  秒
    let second = parseInt(value)
    //  分
    let minute = 0
    //  小时
    let hour = 0
    //  天
    //  let day = 0
    //  如果秒数大于60，将秒数转换成整数
    if (second > 60) {
      //  获取分钟，除以60取整数，得到整数分钟
      minute = parseInt(second / 60)
      //  获取秒数，秒数取佘，得到整数秒数
      second = parseInt(second % 60)
      //  如果分钟大于60，将分钟转换成小时
      // if (minute > 60) {
      //   //  获取小时，获取分钟除以60，得到整数小时
      //   hour = parseInt(minute / 60)
      //   //  获取小时后取佘的分，获取分钟除以60取佘的分
      //   minute = parseInt(minute % 60)
      //   //  如果小时大于24，将小时转换成天
      //   //  if (hour > 23) {
      //   //    //  获取天数，获取小时除以24，得到整天数
      //   //    day = parseInt(hour / 24)
      //   //    //  获取天数后取余的小时，获取小时除以24取余的小时
      //   //    hour = parseInt(hour % 24)
      //   //  }
      // }
    }

    let result = '' + parseInt(second) + '秒'
    if (minute > 0) {
      result = '' + parseInt(minute) + '分' + result
    }
    // if (hour > 0) {
    //   result = '' + parseInt(hour) + '小时' + result
    // }
    //  if (day > 0) {
    //    result = '' + parseInt(day) + '天' + result
    //  }
    return result
  },
  getBrowserType() {
    var userAgent = navigator.userAgent
    var isOpera = userAgent.indexOf('Opera') > -1 // Opera浏览器
    var isIE10orLess = userAgent.indexOf('compatible') > -1 && userAgent.indexOf('MSIE') > -1 // IE10以下
    var isIE11 = userAgent.indexOf('Trident') > -1 && userAgent.indexOf('rv:11.0') > -1 // IE11
    var isFirefox = userAgent.indexOf('Firefox') > -1 // 火狐浏览器
    var isSafari = userAgent.indexOf('Safari') > -1 && userAgent.indexOf('Chrome') === -1 // Safari浏览器
    var isChrome = // 谷歌浏览器
      userAgent.indexOf('Chrome') > -1 && userAgent.indexOf('Safari') > -1 && userAgent.indexOf('Edge') === -1
    // Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36
    var isEdge = userAgent.indexOf('Edge') > -1 && !isIE10orLess // Edge浏览器

    var trident = userAgent.indexOf('Trident') > -1 //IE内核
    var presto = userAgent.indexOf('Presto') > -1 //opera内核
    var webKit = userAgent.indexOf('AppleWebKit') > -1 //苹果、谷歌内核
    var gecko = userAgent.indexOf('Gecko') > -1 && userAgent.indexOf('KHTML') === -1 //火狐内核
    var mobile = !!userAgent.match(/AppleWebKit.*Mobile.*/) //是否为移动终端
    var ios = !!userAgent.match(/\(i[^;]+;( userAgent;)? CPU.+Mac OS X/) //ios终端
    var android = userAgent.indexOf('Android') > -1 || userAgent.indexOf('Adr') > -1 //android终端
    var iPhone = userAgent.indexOf('iPhone') > -1 //是否为iPhone或者QQHD浏览器
    var iPad = userAgent.indexOf('iPad') > -1 //是否iPad
    var webApp = userAgent.indexOf('Safari') === -1 //是否web应该程序，没有头部与底部
    var weixin = userAgent.indexOf('MicroMessenger') > -1 //是否微信 （2015-01-22新增）
    var qq = userAgent.match(/\sQQ/i) === ' qq' //是否QQ
    var windowPhone = userAgent.indexOf('Windows Phone') > -1
    if (isIE10orLess) {
      var reIE = new RegExp('MSIE (\\d+\\.\\d+);')
      reIE.test(userAgent)
      var fIEVersion = parseFloat(RegExp['$1'])
      if (fIEVersion === 7) {
        return 'IE7'
      } else if (fIEVersion === 8) {
        return 'IE8'
      } else if (fIEVersion === 9) {
        return 'IE9'
      } else if (fIEVersion === 10) {
        return 'IE10'
      } else {
        return '0'
      } //IE版本过低
    }
    if (isIE11) {
      return 'IE11'
    }
    if (isFirefox) {
      return 'Firefox'
    }
    if (isOpera) {
      return 'Opera'
    }
    if (isSafari) {
      return 'Safari'
    }
    if (isChrome) {
      return 'Chrome'
    }
    if (isEdge) {
      return 'Edge'
    }
  },
  floatRound(myFloat, mfNumber) {
    if (mfNumber == 0) {
      return Math.round(myFloat)
    } else {
      var cutNumber = Math.pow(10, mfNumber)
      return Math.round((myFloat + 0.000000000001) * cutNumber) / cutNumber
    }
  }
}
export default TOOL

//手机号隐藏中间4位

// export const WB = new wb(["router", "progress"]);
